package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author:YZN
 * @date:2022/12/29
 * @description: 登录过滤器
 */
@WebFilter(urlPatterns = "/*", filterName = "loginCheckFilter")
public class LoginCheckFilter implements Filter {
    //spring提供的路径匹配器
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    /**
     * 过滤器
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //todo 将request和response转换成http格式
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //todo 1.获取本次请求的URL
        String requestURI = request.getRequestURI();
        //todo 2.判断本次请求是否需要处理(登录 注册是不需要处理的)
        //todo 将需要放行的路径放置在string数组中
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login",
                "/order/notify",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs",
                "swagger-ui.html"
        };

        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                //todo 2.1 如果不需要处理直接放行
                filterChain.doFilter(request, response);
                return;
            }
        }
        //todo 3.如果需要处理,判断是否登录状态(request.getsession)
        Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId != null) {

            //todo 3.2 登录状态直接放行 将empId存入ThreadLocal中,方便后期使用
            BaseContext.setCurrenId(empId);
            filterChain.doFilter(request,response);
            return;
        }

        Long user = (Long)request.getSession().getAttribute("user");
        if (user != null){
            //todo 3.2 登录状态直接放行 将empId存入ThreadLocal中,方便后期使用
            BaseContext.setCurrenId(user);
            filterChain.doFilter(request,response);
            return;
        }

        //todo 3.1不是登录状态则拦截
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }
}
